package cn.miao.middle.cloud.core.feign;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.miao.middle.cloud.core.constant.TraceConstant;
import cn.miao.middle.cloud.core.constant.UaaConstant;
import cn.miao.middle.cloud.core.util.TokenUtil;
import feign.RequestInterceptor;

/**
 * feign拦截器
 * 
 * @author kongyufei
 *
 */
@Configuration
public class FeignInterceptorConfig {

	@Bean
	public RequestInterceptor requestInterceptor() {
		RequestInterceptor requestInterceptor = template -> {
			// 传递token
			// 使用feign client访问别的微服务时，将accessToken header
			// config.anyRequest().permitAll() 非强制校验token
			if (StringUtils.isNotBlank(TokenUtil.getToken())) {
				template.header(UaaConstant.TOKEN_HEADER, TokenUtil.getToken());
//            	template.header(UaaConstant.AUTHORIZATION,  OAuth2AccessToken.BEARER_TYPE  +  " "  +  TokenUtil.getToken() );
			}
			// 传递traceId
			String traceId = StringUtils.isNotBlank(MDC.get(TraceConstant.LOG_TRACE_ID))
					? MDC.get(TraceConstant.LOG_TRACE_ID)
					: MDC.get(TraceConstant.LOG_B3_TRACEID);
			if (StringUtils.isNotBlank(traceId)) {
				template.header(TraceConstant.HTTP_HEADER_TRACE_ID, traceId);
			}

		};

		return requestInterceptor;
	}
}
